type Callback = (...args: any[]) => void;

type Callbacks = Callback[];

type CallbackMap = {
  // 路由 onMounted 触发
  ON_MOUNTED?: Callbacks;
};

export default class EventBus {
  static CALLBACK_MAP: CallbackMap = {};

  // 订阅
  static $on(type: keyof CallbackMap, callback: Callback) {
    if (this.CALLBACK_MAP[type]) {
      this.CALLBACK_MAP[type]?.push(callback);
    } else {
      this.CALLBACK_MAP[type] = [callback];
    }
  }

  // 解绑
  static $off(type: keyof CallbackMap, callback?: Callback) {
    const callbacks = this.CALLBACK_MAP[type];

    if (!callbacks || !callbacks.length) {
      return;
    }

    if (callback) {
      const findIndex = callbacks.findIndex(
        (_callback) => _callback === callback
      );

      findIndex >= 0 && callbacks.splice(findIndex, 1);
    } else {
      this.CALLBACK_MAP[type] = [];
    }
  }

  // 触发
  static $emit(type: keyof CallbackMap, ...args: any[]) {
    const callbacks = this.CALLBACK_MAP[type];
    callbacks &&
      callbacks.length &&
      callbacks.forEach((callback) => callback(...args));
  }
}
